package controller

import (
	"SystemExploration/ability"
	"SystemExploration/mongodb"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"time"
)

type Users struct{}

// 路由
func (that *Users) Router(engine *gin.RouterGroup) {
	engine.POST("/admin/login", that.Login)
}

func (that *Users) Login(c *gin.Context) {
	loginRequest := loginRequest{}
	if err := c.ShouldBind(&loginRequest); err != nil {
		c.JSON(200, gin.H{
			"code": "402",
			"msg":  "参数错误",
		})
		return
	}

	//查数据库有没有
	userinfo := new(mongodb.Users)
	filter := bson.D{{"username", loginRequest.UserName},
		{"password", loginRequest.PassWord},
	}
	err := mongodb.FindUserOne(filter, userinfo)
	if err != nil {
		c.JSON(200, gin.H{
			"code": "403",
			"msg":  "没有这个用户",
		})
		return
	}

	//生成token
	j := ability.NewJWT()

	// 构造用户claims信息(负荷)
	claims := ability.CustomClaims{
		Name: userinfo.Username,
		Prx:  userinfo.Prx,
		StandardClaims: jwt.StandardClaims{
			NotBefore: int64(time.Now().Unix() - 1000), // 签名生效时间
			ExpiresAt: int64(time.Now().Unix() + 7200), // 签名过期时间
			Issuer:    "JwAdmin.cc",                    // 签名颁发者
		},
	}

	// 根据claims生成token对象
	token, err := j.CreateToken(claims)

	if err != nil {
		c.JSON(200, gin.H{
			"code": "404",
			"msg":  "认证生成失败",
		})
		return
	}

	loginRespone := loginRespone{
		Code:  "200",
		Msg:   "成功",
		Token: token,
	}
	c.JSON(200, loginRespone)
	return
}
